#include "chat_server.h"

#include "netlib/base/logger.h"

using namespace std::placeholders;

ChatServer::ChatServer(net::EventLoop* loop, net::InetAddress addr) :
    loop_(loop), server_(loop, addr, "ChatServer"),
    codec_([this](const net::TcpConnectionPtr& conn, const std::string& msg, Timestamp time) {
	    OnStringMessage(conn, msg, time);
    }) {
	server_.SetConnectionCallback(
	    [this](const net::TcpConnectionPtr& conn) { OnConnection(conn); });
	server_.SetMessageCallback(
	    [&codec = codec_](const net::TcpConnectionPtr& conn, net::Buffer* buf, Timestamp time) {
		    codec.OnMessage(conn, buf, time);
	    });
}

void ChatServer::OnConnection(const net::TcpConnectionPtr& conn) {
	LOG_INFO << "ChatServer : " << conn->LocalAddress().ToIpPort() << "<->"
	         << conn->PeerAddress().ToIpPort() << " is " << (conn->Connected() ? "UP" : "DOWN");
	if (conn->Connected()) {
		connections_.insert(conn);
	} else {
		connections_.erase(conn);
	}
}

void ChatServer::OnStringMessage(const net::TcpConnectionPtr& conn,
                                 const std::string& msg,
                                 Timestamp time) {
	for (const auto& connection : connections_) {
		if (connection == conn) {
			continue;
		}
		codec_.Send(connection, msg);
	}
}
